package com.nuo.search;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class WebSearch {
	
	public static final String WEB_CHAR = "gb2312";
	public static int deep = 2;
	public static int total = 0;
	
	public void searchByUrl(String url, String matchName){
		URL toUrl;
		
		HttpURLConnection con = null;
		InputStream is = null;
		try {
			toUrl = new URL(url);
			
			
			
			con = (HttpURLConnection) toUrl.openConnection();
			is = con.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, WEB_CHAR));
			String content = null;
			while((content =  br.readLine()) != null){
				//System.out.println(content);
				int index = -1;
				do{
					index = content.indexOf("href", index + 1);
					if(index != -1){
						int start = content.indexOf("\"", index + 1);
						int end = content.indexOf("\"", start + 1);
						String result = content.substring(start + 1, end);
						if(result.startsWith("http")){
							URL subUrl = new URL(result);
							this.matchName(subUrl, matchName);
						}else if(result.startsWith("/")){
							URL subUrl = new URL(toUrl.getProtocol() + "://" + toUrl.getHost() + result);
							this.matchName(subUrl, matchName);
						}else{
							//TODO
							//相对路径太复杂啦　等日后。
						}
					}
				}while(index > 0 && index < content.length());
			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(con != null){
				con.disconnect();
			}
		}
	}
	
	public void matchName(URL url, String name) throws IOException{
		
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		InputStream is = con.getInputStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is, WEB_CHAR));
		String content = null;
		while((content =  br.readLine()) != null){
			if(content.contains(name)){
				System.out.println("找到数据：" + url);
			}
		}
		if(is != null){
			is.close();
		}
		if(con != null){
			con.disconnect();
		}
		
		System.out.println(url);
	}
	
	
	public static void main(String[] args) throws MalformedURLException, IOException {
		new WebSearch().searchByUrl("http://99.99btgc.com/00/11.html", "麻生希");
		//new WebSearch().matchName(new URL("http://99.99btgc.com/p2p/01/13-01-30-23-36-45.html"), "中文");
	}
	
}
